<?php
    // put all controller wide functions in here. like filters
    class Application extends ActionController 
    {        
        
        function is_logged_in($redirect=true)
        {             
           // check cookies first           
           if(!empty($_SESSION['user_id']) 
              && is_numeric($_SESSION['user_id'])
              && $_SESSION['user_id'] > 0){    
               return true;
           } else { 
              // /*
               use_pixel_lib('class.cookie.php');
               $cookie = new clsCookie('pixelapp');
               $cookie->init();
               $secret_user   = create_hash('user_login'.COOKIECRYPTKEY.$_SERVER['REMOTE_ADDR']);
               $secret_pass   = create_hash('user_pass'.COOKIECRYPTKEY.$_SERVER['REMOTE_ADDR']);
               if(isset($cookie->aValues[$secret_user])){
                  use_model('users');
                  $u = new Users();
                  
                  // stuff from cookie
                  $pass          = $cookie->aValues[$secret_pass];               
                  $login_user    = $cookie->aValues[$secret_user];
                  
                  // get user id
                  $user_pass     = $u->get_user_password($login_user);
                  
                  // check that userid is valid      
                  $pass_check    = create_hash(COOKIECRYPTKEY.$user_pass);
                  
                  if($pass != $pass_check ) {                      
                      if ($redirect) $this->redirect_to_login();
                      return false;
                  }

                  // userid is valid, log em in danno
                  $id = $u->get_user_id($login_user);                                        
                  if($id){
                     session_regenerate_id();
                     $_SESSION['user_id'] = $id;
                     return true;
                  }
               }
              // */
               if ($redirect) $this->redirect_to_login();
               return false;
           }
        }
        
        
        function logout_user()
        {
            $_SESSION = array();
            session_destroy();
            //*
            use_pixel_lib('class.cookie.php');
            $cookie = new clsCookie('pixelapp');
            $cookie->init();
            $cookie->destroy();
            //*/
            
        }
        
        function redirect_to_login()
        {
            $_SESSION['login_referrer'] = htmlspecialchars($_SERVER['REQUEST_URI']);
            $this->redirect_to(get_installed_path().'/login');
        }
        
    }

?>